package com.joolun.web.controller.scrm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.corundumstudio.socketio.SocketIOClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.joolun.common.annotation.Anonymous;
import com.joolun.common.annotation.Log;
import com.joolun.common.core.controller.BaseController;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.core.domain.entity.SysDept;
import com.joolun.common.core.domain.entity.SysUser;
import com.joolun.common.core.domain.model.LoginUser;
import com.joolun.common.core.page.PageDomain;
import com.joolun.common.core.page.TableDataInfo;
import com.joolun.common.core.page.TableSupport;
import com.joolun.common.core.redis.RedisCache;
import com.joolun.common.corp.TenantContext;
import com.joolun.common.enums.BusinessType;
import com.joolun.common.utils.SecurityUtils;
import com.joolun.common.utils.poi.ExcelUtil;
import com.joolun.framework.socket.ClientCache;
import com.joolun.framework.socket.MessageInfo;
import com.joolun.system.domain.SysCorpConfig;
import com.joolun.system.service.ISysDeptService;
import com.joolun.system.service.ISysRoleService;
import com.joolun.system.service.ISysUserService;
import com.joolun.system.service.impl.SysCorpConfigServiceImpl;
import com.joolun.web.huantuo.MTCloud;
import com.joolun.weixin.entity.ZbRoom;
import com.joolun.weixin.entity.ZbVideo;
import com.joolun.weixin.entity.vo.ZbRoomVo;
import com.joolun.weixin.service.IZbRoomService;
import com.joolun.weixin.service.IZbVideoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 直播间信息Controller
 * 
 * @author joolun
 * @date 2025-04-24
 */
@RestController
@RequestMapping("/zb/room")
public class ZbRoomController extends BaseController
{
    @Autowired
    private IZbRoomService zbRoomService;

    @Autowired
    private ClientCache clientCache;

    @Autowired
    private IZbVideoService zbVideoService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysCorpConfigServiceImpl sysCorpConfigService;

    @Resource
    private RedisCache redisCache;

    // 使用ObjectMapper库解析JSON字符串
    ObjectMapper mapper = new ObjectMapper();

    // 根据登录用户获取openID和openToken
    public MTCloud getOpenIDAndOpenToken(){
        // 获取当前登录的用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 获取当前登录用户的部门
        SysDept dept = user.getDept();
        // 获取父级部门id
        Long parentId = dept.getParentId();
        // 获取父级部门对象
        SysDept parentDept = deptService.selectDeptById(parentId);
        System.out.println("OpenIdHt---------------" + parentDept.getOpenIdHt());
        if((parentDept.getOpenIdHt() != null && parentDept.getOpenIdHt() != "") && (parentDept.getOpenTokenHt() != null && parentDept.getOpenTokenHt() != "")){
            // 根据用户所属公司获取公司的openID和openToken
            return new MTCloud(parentDept.getOpenIdHt(),parentDept.getOpenTokenHt());
        }
        MTCloud mtCloud = new MTCloud();
        return mtCloud;
    }


    @GetMapping("/user/{userId}")
    @Anonymous
    public String pushTuUser(@PathVariable("userId") String userId){
        SocketIOClient userClient = clientCache.getUserClient(userId);
        //向客户端推送消息
        userClient.sendEvent("chatevent",new MessageInfo("管理员","向客户段发送的消息"));
        return "success";
    }

    /**
     * 查询直播间信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ZbRoom zbRoom)
    {
        startPage();
        String corpId = TenantContext.getTenantId();
        System.out.println("corpId-----------------------" + corpId);
        // 欢拓接口
        MTCloud mtCloud = getOpenIDAndOpenToken();
        List<ZbRoom> listZbRoom = zbRoomService.selectZbRoomList(zbRoom);
        List<ZbRoomVo> resultRoom = new ArrayList<>();
        try {
            HashMap<Object,Object> options = new HashMap<>();
            // 课程状态：0 为正常状态，-1 为已删除
            options.put("status", 0);
            // 分类id，默认分类
//            options.put("groupId", 0);
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            String htResult = mtCloud.courseList(null,null, pageNum, 1000, options);
            // 将返回结果转换为map
            Map<String, Object> htMap = mapper.readValue(htResult, Map.class);
            List<Map<String, Object>> htList = (List<Map<String, Object>>) htMap.get("data");

            if(htList != null  && !htList.isEmpty()){
                Map<String, Map<String, Object>> detailMap = htList.stream()
                        .filter(item -> item.get("course_id") != null) // 过滤掉course_id为null的项
                        .collect(Collectors.toMap(item -> (String) item.get("course_id"), item -> item));
                resultRoom = listZbRoom.stream()
                        .filter(room -> room.getId() != null && detailMap.containsKey(room.getId().toString()))
                        .map(room -> {
                    ZbRoomVo zbRoomVo = new ZbRoomVo();
                    zbRoomVo.setId(room.getId());
                    zbRoomVo.setTitle(room.getTitle());
                    zbRoomVo.setStartTime(room.getStartTime());
                    zbRoomVo.setEndTime(room.getEndTime());
                    zbRoomVo.setType(room.getType());
                    zbRoomVo.setZhubo(room.getZhubo());
                    zbRoomVo.setConfigId(room.getConfigId());
                    zbRoomVo.setVideoSource(room.getVideoSource());
                    zbRoomVo.setModel(room.getModel());
                    zbRoomVo.setStatus(room.getStatus());
                    zbRoomVo.setCreateBy(room.getCreateBy());
                    zbRoomVo.setUpdateBy(room.getUpdateBy());
                    zbRoomVo.setCreateTime(room.getCreateTime());
                    zbRoomVo.setUpdateTime(room.getUpdateTime());
                    zbRoomVo.setRemark(room.getRemark());
                    zbRoomVo.setVideoId(room.getVideoId());
                    zbRoomVo.setUrl(room.getUrl());
                    zbRoomVo.setCourseId(room.getCourseId());
                    Long id = room.getId();
                    zbRoomVo.setHtZbRoom(detailMap.get(id.toString()));
                    System.out.println("room ID: " + id + ", htRoom: " + detailMap.get(id.toString()));
                    return zbRoomVo;
                }).collect(Collectors.toList());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return getDataTableAndTotal(resultRoom,new PageInfo(listZbRoom).getTotal());
    }
    /**
     * 根据课程id查询直播地址
     */
    @Anonymous
    @GetMapping("/zbUrl")
    public AjaxResult getZbUrl(String zbId,String uid,String nickname, String role, String avatar)
    {
        // 根据直播id获取直播信息
        ZbRoom zb = zbRoomService.selectZbRoomById(Long.parseLong(zbId));
        System.out.println("--------------ZbRoom-----------------" + zb);
        // 根据主体id查询主体配置
        SysCorpConfig sysCorp = sysCorpConfigService.getOne(new QueryWrapper<SysCorpConfig>().eq("corp_id", zb.getCorpId()), false);
        // 加载欢拓
        MTCloud mtCloud = new MTCloud(sysCorp.getOpenIdHt(),sysCorp.getOpenTokenHt());
        Map<String, Object> htList = new HashMap<>();
        String htResult = "";
        try {
            HashMap<Object,Object> options = new HashMap<>();
            options.put("avatar", avatar);
            htResult = mtCloud.courseAccess(zbId,uid,nickname,role,7200,options);
            // 将返回结果转换为map
            Map<String, Object> htMap = mapper.readValue(htResult, Map.class);
            System.out.println("欢拓直播地址---------------" + htMap);
            htList = (Map<String, Object>) htMap.get("data");
            // 返回直播信息
            htList.put("zbRoom", zb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success(htList);
    }
    /**
     * 根据课程id查询回放地址
     */
    @GetMapping("/backUrl")
    public AjaxResult getBackUrl(String zbId,String uid,String nickname, String role, String avatar)
    {
        // 欢拓接口
        MTCloud mtCloud = getOpenIDAndOpenToken();
        Map<String, Object> htList = new HashMap<>();
        String htResult = "";
        try {
            HashMap<Object,Object> options = new HashMap<>();
            options.put("avatar", avatar);
            htResult = mtCloud.courseAccessPlayback(zbId,uid,nickname,role,7200,options);
            // 将返回结果转换为map
            Map<String, Object> htMap = mapper.readValue(htResult, Map.class);
            htList = (Map<String, Object>) htMap.get("data");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success(htList);
    }
    /**
     * 根据课程id查询数据魔方
     */
    @GetMapping("/reportUrl")
    public AjaxResult getReportUrl(Integer zbId,String report)
    {
        // 欢拓接口
        MTCloud mtCloud = getOpenIDAndOpenToken();
        Map<String, Object> htList = new HashMap<>();
        String htResult = "";
        try {
            HashMap<Object,Object> options = new HashMap<>();
            options.put("path", report);
            htResult = mtCloud.courseThirdAuthPath(zbId,options);
            // 将返回结果转换为map
            Map<String, Object> htMap = mapper.readValue(htResult, Map.class);
            htList = (Map<String, Object>) htMap.get("data");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success(htList);
    }
    /**
     * 导出直播间信息列表
     */
    @PreAuthorize("@ss.hasPermi('zb:room:export')")
    @Log(title = "直播间信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZbRoom zbRoom)
    {
        List<ZbRoom> list = zbRoomService.selectZbRoomList(zbRoom);
        ExcelUtil<ZbRoom> util = new ExcelUtil<ZbRoom>(ZbRoom.class);
        util.exportExcel(response, list, "直播间信息数据");
    }

    /**
     * 获取直播间详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        // 欢拓接口
//        MTCloud mtCloud = getOpenIDAndOpenToken();
        MTCloud mtCloud = new MTCloud();
        Map<String, Object> htList = new HashMap<>();
        String htResult = "";
        try {
            HashMap<Object,Object> options = new HashMap<>();
            htResult = mtCloud.courseGet(id.toString(),options);
            // 将返回结果转换为map
            Map<String, Object> htMap = mapper.readValue(htResult, Map.class);
            htList.put("data", htMap.get("data"));
            ZbRoom zb = zbRoomService.selectZbRoomById(id);
            htList.put("zbRoom", zb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success(htList);
    }

    /**
     * 新增直播间信息
     */
    @PreAuthorize("@ss.hasPermi('zb:room:add')")
    @Log(title = "直播间信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZbRoom zbRoom)
    {
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            HashMap<Object,Object> options = new HashMap<>();
            // 1=伪直播，2-主播模式
            if("1".equals(zbRoom.getType())){
                // 伪直播参数
                // 8-关联剪辑 9-关联课程回放，10-关联视频
                options.put("relateType", zbRoom.getVideoSource());
                ZbVideo video = zbVideoService.selectZbVideoById(Long.parseLong(zbRoom.getUrl()));
                // 视频id
                options.put("relateId", video.getId());
                // 伪直播时，是否发送原课程的聊天：1 是，0 否
                options.put("relateChat", "1");
            }
            // 生活直播，可添加商品
            options.put("scenes", "2");
            // 默认密码
            options.put("password", "zgkj1234");
            // 根据直播老师id查询老师信息
            SysUser sysUser = userService.selectUserById(Long.parseLong(zbRoom.getZhubo()));
            String htResult = mtCloud.courseAdd(zbRoom.getTitle(), zbRoom.getZhubo(), zbRoom.getStartTime(), zbRoom.getEndTime(), sysUser.getNickName(), "", options);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            Map<String, Object> dataMap = (Map<String, Object>) map.get("data");
            // data存在，创建成功
            if (dataMap != null && !dataMap.isEmpty()) {
                // dataMap存在且包含键值对
                System.out.println("---------------------start创建欢拓课程成功---------------");
                for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                    // 保存欢拓的课程id
                    if("course_id".equals(entry.getKey())){
                        zbRoom.setId(Long.parseLong(entry.getValue().toString()));
                    }
                    System.out.println(entry.getKey() + ": " + entry.getValue());
                }
                System.out.println("---------------------end创建欢拓课程成功---------------");
                // 同步到后台创建直播间
                zbRoom.setCreateBy(getUsername());
                return toAjax(zbRoomService.insertZbRoom(zbRoom));
            } else {
                String msg = map.get("msg").toString();
                System.out.println("---------------------创建欢拓课程失败---------------" + htResult);
                return error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    /**
     * 修改直播间信息
     */
    @PreAuthorize("@ss.hasPermi('zb:room:edit')")
    @Log(title = "直播间信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZbRoom zbRoom)
    {
        zbRoom.setCreateBy(getUsername());
        return toAjax(zbRoomService.updateZbRoom(zbRoom));
    }

    /**
     * 删除直播间信息
     */
    @PreAuthorize("@ss.hasPermi('zb:room:remove')")
    @Log(title = "直播间信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            String id = "null";
            if(ids != null && ids.length > 0){
                id = ids[0].toString();
            }
            String htResult = mtCloud.courseDelete(id);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            String dataMap =  map.get("code").toString();
            // data存在，创建成功
            if ("0".equals(dataMap)) {
                // 同步后台删除直播
                return toAjax(zbRoomService.deleteZbRoomByIds(ids));
            } else {
                String msg = map.get("msg").toString();
                System.out.println("---------------------删除失败---------------" + htResult);
                return error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    /**
     * 根据直播id查询直播用户列表
     */
    @PostMapping("/zbUserList")
    public TableDataInfo getZbUserList(@RequestBody Map<String, Object> params)
    {
        String roomId = (String) params.get("roomId");
        Long page = Long.parseLong(params.get("pageNum").toString());
        Long size = Long.parseLong(params.get("pageSize").toString());
        List<Object> list = new ArrayList<>();
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            HashMap<Object,Object> options = new HashMap<>();
            String htResult =  mtCloud.courseVisitorList(roomId, page, size, options);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            list = (List<Object>) map.get("data");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getDataTableAndTotal(list, new PageInfo(list).getTotal());
    }

    /**
     * 根据直播id查询聊天记录
     */
    @PostMapping("/zbChatList")
    public TableDataInfo getZbChatList(@RequestBody Map<String, Object> params)
    {
        String roomId = (String) params.get("roomId");
        Long page = Long.parseLong(params.get("pageNum").toString());
        Long size = Long.parseLong(params.get("pageSize").toString());
        List<Object> list = new ArrayList<>();
        try {
            // 欢拓接口
            MTCloud mtCloud = getOpenIDAndOpenToken();
            String htResult =  mtCloud.courseMessageList(roomId, page, size);
            // 将返回结果转换为map
            Map<String, Object> map = mapper.readValue(htResult, Map.class);
            // 访问内部data字段
            list = (List<Object>) map.get("data");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getDataTableAndTotal(list, new PageInfo(list).getTotal());
    }
}
